<template>
<div>
 <el-card>
   <el-alert
       show-icon
       title="注意:只允许为第三级分类设置相关参数!"
       type="warning"
        :closable="false">
   </el-alert>
   <el-row class="cat_opt">
     <el-col>
       <span>选择商品分类：</span>
       <el-cascader
           clearable
           v-model="selectedKeys"
           :options="categoryList"
           :props="cascaderProps"
           @change="parentCateChange" popper-class="CateCascader" class="CateCascader"></el-cascader>
     </el-col>
   </el-row>

   <el-tabs v-model="activeName" @tab-click="handleTabClick">
     <el-tab-pane label="动态参数" name="many">
       <el-button class="addBtn" type="primary" size="mini" :disabled="isBtn" @click="showAddParams">添加属性</el-button>
       <el-table :data="tableData" border stripe>
<!--         展开行-->
         <el-table-column type="expand">
           <template v-slot="scope">
             <el-tag disable-transitions closable @close="handleClose(index,scope.row)" class="itemTag" v-for="(item, index) in scope.row.attr_vals" :key="index">
               {{ item }}
             </el-tag>
             <el-input
                 class="input-new-tag"
                 v-if="scope.row.inputVisible"
                 v-model="scope.row.inputValue"
                 ref="saveTagInput"
                 size="small"
                 @keyup.enter.native="handleInputConfirm(scope.row)"
                 @blur="handleInputConfirm(scope.row)"
             >
             </el-input>
             <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>


           </template>
         </el-table-column>
         <el-table-column type="index" label="#"></el-table-column>
         <el-table-column label="参数名称" prop="attr_name"></el-table-column>
         <el-table-column label="操作">
           <template v-slot="scope">
             <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParams(scope.row.attr_id,scope.row.attr_name)">编辑</el-button>
             <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
           </template>
         </el-table-column>
       </el-table>
     </el-tab-pane>
     <el-tab-pane label="静态属性" name="only">
       <el-button class="addBtn" type="primary" size="mini" :disabled="isBtn" @click="showAddParams">添加属性</el-button>
       <el-table :data="tableData" border stripe>
         <!--         展开行-->
         <el-table-column type="expand">
           <template v-slot="scope">
             <el-tag disable-transitions closable @close="handleClose(index,scope.row)" class="itemTag" v-for="(item, index) in scope.row.attr_vals" :key="index">
               {{ item }}
             </el-tag>
             <el-input
                 class="input-new-tag"
                 v-if="scope.row.inputVisible"
                 v-model="scope.row.inputValue"
                 ref="saveTagInput"
                 size="small"
                 @keyup.enter.native="handleInputConfirm(scope.row)"
                 @blur="handleInputConfirm(scope.row)"
             >
             </el-input>
             <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>


           </template>
         </el-table-column>
         <el-table-column type="index" label="#"></el-table-column>
         <el-table-column label="属性名称" prop="attr_name"></el-table-column>
         <el-table-column label="操作">
           <template v-slot="scope">
             <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParams(scope.row.attr_id,scope.row.attr_name)">编辑</el-button>
             <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
           </template>
         </el-table-column>
       </el-table>
     </el-tab-pane>
   </el-tabs>

 </el-card>

<!--  添加属性-->
  <el-dialog :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'" :visible.sync="addParamsDialog" @close="addParamsDialogClose('addParamsDialog')">
    <el-form label-width="100px" ref="addParamsDialog" :rules="addParamsRules" :model="addParamsForm">
      <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
        <el-input v-model="addParamsForm.attr_name"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
  </el-dialog>

  <!--  修改属性-->
  <el-dialog :title="activeName == 'many' ? '修改动态参数' : '修改静态属性'" :visible.sync="editParamsDialog" @close="addParamsDialogClose('editParamsDialog')">
    <el-form label-width="100px" ref="editParamsDialog" :rules="addParamsRules" :model="editParamsForm">
      <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
        <el-input v-model="editParamsForm.attr_name"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
  </el-dialog>


</div>
</template>

<script>

import {remove} from "@/network/remove";

export default {
  name: "params",
  data(){
    return{
      categoryList:[],
      cascaderProps:{
        expandTrigger: 'hover',
        value:'cat_id',
        label:'cat_name',
        children:'children',
      },
      selectedKeys:[],
      activeName:"many",
      tableData:[],
      //添加参数对话框
      addParamsDialog:false,
      addParamsRules:{
        attr_name:[{
          required: true,
          message: '请输入分类名',
          trigger: 'blur'
        }]
      },
      addParamsForm:{
        attr_name:'',
      },

    //  修改属性
      editParamsDialog:false,
      editParamsForm:{
        attr_id:0,
        attr_name:'',
      },

    }
  },
  created() {
    this.getCateList()
  },
  methods:{
    async getCateList(){
      const {data:res} = await this.$http.get('categories')
      // console.log(res);
      if (res.meta.status !== 200) return this.$Message.error("获取失败")
      this.categoryList = res.data

    },
    async parentCateChange(){
      // console.log(this.selectedKeys);
if (this.selectedKeys.length !== 3) return

      const {data:res} = await this.$http.get(`categories/${this.selectedKeys[2]}/attributes`,{
        params:{sel:this.activeName}
      })
      if (res.meta.status !== 200) return this.$Message.error("获取失败")

      res.data.forEach(item => {
       item.attr_vals = item.attr_vals ? item.attr_vals.split(','):[]
        this.$set(item,'inputVisible',false)
        this.$set(item,'inputValue','')
      })
      // console.log(res)
this.tableData = res.data

    },
    handleTabClick(){
    this.parentCateChange()
    },
    addParamsDialogClose(ref){
      this.$refs[ref].resetFields()
      this.editParamsForm.attr_id=0
      this.editParamsForm.attr_name=''
      this.addParamsForm.attr_name=''
    },
    showAddParams(){
      this.addParamsDialog = true
    },
    addParams(){
      this.$refs.addParamsDialog.validate(async valid =>{
        if (!valid) return
       const {data:res} = await this.$http.post(`categories/${this.selectedKeys[2]}/attributes`,{
         attr_name:this.addParamsForm.attr_name,
         attr_sel:this.activeName
       })
        if (res.meta.status !== 201) return this.$Message.error("失败")
        this.parentCateChange()
        this.addParamsDialog=false

      } )
    },
    showEditParams(id,name) {
     this.editParamsForm.attr_id=id
     this.editParamsForm.attr_name=name

      this.editParamsDialog=true
    },
    editParams(){

      this.$refs.editParamsDialog.validate(async valid =>{
        if (!valid) return
        const {data:res} = await this.$http.put(`categories/${this.selectedKeys[2]}/attributes/${this.editParamsForm.attr_id}`,{
          attr_name:this.editParamsForm.attr_name,
          attr_sel:this.activeName
        })
        if (res.meta.status !== 200) return this.$Message.error("失败")
        this.parentCateChange()
        this.editParamsDialog=false

      })

    },
    removeParams(id){
      remove(`categories/${this.selectedKeys[2]}/attributes/${id}`,this.parentCateChange)
    },
    async handleInputConfirm(row){
      if (row.inputValue.trim().length === 0){
        row.inputValue=''
        row.inputVisible = false
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue=''
      row.inputVisible = false

      this.setAttrVals(row)

      // this.parentCateChange()

    },
    handleClose(index,row){
      row.attr_vals.splice(index,1)
      this.setAttrVals(row)

    },
    showInput(row){
      row.inputVisible=true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async setAttrVals(row){
      const {data:res} = await this.$http.put(`categories/${this.selectedKeys[2]}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(','),

      })
      if (res.meta.status !== 200) return this.$Message.error("失败")
    }
  },
  computed:{
    isBtn(){
      return this.selectedKeys.length !== 3
    }
  }
}
</script>

<style>
.cat_opt{
  margin: 15px 0;
}
.itemTag{
  margin: 15px;
}
.el-cascader-menu{height:300px}
.input-new-tag{
  width: 120px;
  margin: 15px;
}
.button-new-tag{
  margin: 15px;
}
.addBtn{
  margin-bottom: 15px;
}
</style>